/* eslint-disable no-undef */
<template>
	<div class="game-container report-container">
		<div class="view-container dealer-container">
			<header>
				<el-tabs v-model="activeName" @tab-click="handleClick">
					<el-tab-pane
						v-if="
							+rowData.entranceEnable !== 0 ||
								rowData.activityType == 1
						"
						:label="$t('operation.activity_list.detail1')"
						name="first"
					>
						<div class="params">
							<el-form
								ref="form"
								:inline="true"
								:model="queryData"
							>
								<el-form-item>
									<el-input
										v-model="queryData.optionsValue"
										maxlength="14"
										clearable
										:placeholder="$t('common.please_enter')"
									>
										<el-select
											slot="prepend"
											v-model="queryData.options"
											:placeholder="
												$t('common.please_choose')
											"
											style="width:120px"
										>
											<el-option
												:label="
													$t(
														'operation.activity_list.member_account'
													)
												"
												value="userName"
											></el-option>
											<el-option
												:label="
													$t(
														'operation.activity_list.top_agent'
													)
												"
												value="parentProxyName"
											></el-option>
										</el-select>
									</el-input>
								</el-form-item>
								<el-form-item
									class="time-options"
									:label="
										$t('operation.activity_list.apply_time')
									"
								>
									<el-date-picker
										v-model="queryData.searchTime"
										size="medium"
										:picker-options="pickerOptions"
										format="yyyy-MM-dd HH:mm:ss"
										type="datetimerange"
										range-separator="-"
										:start-placeholder="
											$t('common.start_date')
										"
										:end-placeholder="$t('common.end_date')"
										align="right"
										:clearable="true"
										:default-time="defaultTime"
										style="width: 375px"
										class="time-options-value"
									></el-date-picker>
								</el-form-item>

								<el-form-item>
									<el-button
										type="primary"
										icon="el-icon-search"
										:disabled="loading"
										size="medium"
										@click="search"
									>
										{{ $t('common.search') }}
									</el-button>
									<el-button
										icon="el-icon-refresh-left"
										:disabled="loading"
										size="medium"
										@click="reset"
									>
										{{ $t('common.reset') }}
									</el-button>
									<el-button
										icon="el-icon-download"
										type="warning"
										:disabled="loading"
										size="medium"
										@click="exportExcel"
									>
										{{ $t('common.export') }}
									</el-button>
								</el-form-item>
							</el-form>
						</div>
						<div class="content">
							<el-table
								v-loading="loading"
								element-loading-spinner="el-icon-loading"
								border
								size="mini"
								class="small-size-table"
								:data="tableData"
								style="width: 100%"
								:header-cell-style="getRowClass"
								@sort-change="_changeTableSort"
							>
								<el-table-column
									key="index"
									type="index"
									align="center"
									:label="$t('common.serial_number')"
									width="100"
								></el-table-column>
								<el-table-column
									prop="userName"
									align="center"
									:label="
										$t(
											'operation.activity_list.member_account'
										)
									"
									width="150"
								>
									<template slot-scope="scope">
										{{ scope.row.userName || '-' }}
									</template>
								</el-table-column>
								<el-table-column
									prop="vipId"
									align="center"
									:label="
										$t('operation.activity_list.vip_level')
									"
									width="220"
								>
									<template slot-scope="scope">
										{{ scope.row.vipSerialNum || 0 }}
									</template>
								</el-table-column>
								<el-table-column
									prop="windControlName"
									align="center"
									:label="
										$t('operation.activity_list.risk_level')
									"
									width="220"
								>
									<template slot-scope="scope">
										{{ scope.row.windControlName || '-' }}
									</template>
								</el-table-column>
								<el-table-column
									prop="parentProxyName"
									align="center"
									:label="
										$t('operation.activity_list.top_agent')
									"
									width="220"
								>
									<template slot-scope="scope">
										{{
											(scope.row.parentProxyName ===
												'0' ||
											scope.row.parentProxyName === 0
												? '-'
												: scope.row.parentProxyName) ||
												'-'
										}}
									</template>
								</el-table-column>
								<el-table-column
									prop="deviceType"
									align="center"
									:label="
										$t('operation.activity_list.terminal')
									"
									width="220"
								>
									<template slot-scope="scope">
										{{
											filterDeviceType(
												scope.row.deviceType
											) || '-'
										}}
									</template>
								</el-table-column>
								<!-- <el-table-column
									v-if="rowData.name1 !== '首存活动'"
									prop="deviceNo"
									align="center"
									label="展示设备"
									width="220"
								>
									<template slot-scope="scope">
										{{ filterAppID(scope.row.loginAppId) || '-' }}
									</template>
								</el-table-column> -->
								<el-table-column
									v-if="rowData.activityType == 1"
									prop="upAmount"
									align="center"
									:label="
										$t(
											'operation.activity_list.apply_monney'
										)
									"
									width="300"
								>
									<template slot-scope="scope">
										{{ scope.row.upAmount || '-' }}
									</template>
								</el-table-column>
								<el-table-column
									v-if="rowData.activityType == 1"
									prop="gameCode"
									align="center"
									:label="
										$t(
											'operation.activity_list.apply_venue'
										)
									"
									width="300"
								>
									<template slot-scope="scope">
										{{
											typeFilter(
												scope.row.gameCode,
												'bwVenueList'
											)
										}}
									</template>
								</el-table-column>
								<el-table-column
									v-if="rowData.activityType == 1"
									prop="bonusAmount"
									align="center"
									:label="
										$t(
											'operation.activity_list.bonus_money'
										)
									"
									width="300"
								>
									<template slot-scope="scope">
										{{ scope.row.bonusAmount || '-' }}
									</template>
								</el-table-column>
								<el-table-column
									prop="createdAt"
									align="center"
									sortable="custom"
									:label="
										$t('operation.activity_list.apply_time')
									"
									width="300"
								>
									<template slot-scope="scope">
										{{ scope.row.createdAt || '-' }}
									</template>
								</el-table-column>
							</el-table>
							<!-- 分页 -->
							<el-pagination
								v-show="tableData.length > 0"
								class="pageValue"
								:current-page.sync="pageNum"
								background
								layout="total, sizes,prev, pager, next, jumper"
								:page-size="pageSize"
								:page-sizes="[10, 20, 50]"
								:total="total"
								@current-change="handleCurrentChange"
								@size-change="handleSizeChange"
							></el-pagination>
						</div>
					</el-tab-pane>
					<el-tab-pane
						:label="$t('operation.activity_list.statistics')"
						name="second"
					>
						<div class="params">
							<el-form
								ref="form"
								:inline="true"
								:model="queryData"
							>
								<el-form-item
									class="time-options"
									:label="
										$t(
											'operation.activity_list.access_time'
										)
									"
								>
									<el-date-picker
										v-model="searchTime"
										size="medium"
										:picker-options="pickerOptions"
										format="yyyy-MM-dd HH:mm:ss"
										type="datetimerange"
										range-separator="-"
										:start-placeholder="
											$t('common.start_date')
										"
										:end-placeholder="$t('common.end_date')"
										align="right"
										:clearable="true"
										:default-time="defaultTime"
										style="width: 375px"
										class="time-options-value"
									></el-date-picker>
								</el-form-item>

								<el-form-item>
									<el-button
										type="primary"
										icon="el-icon-search"
										:disabled="loading"
										size="medium"
										@click="search1"
									>
										{{ $t('common.search') }}
									</el-button>
									<el-button
										icon="el-icon-refresh-left"
										:disabled="loading"
										size="medium"
										@click="reset1"
									>
										{{ $t('common.reset') }}
									</el-button>
								</el-form-item>
							</el-form>
						</div>
						<statistics
							v-if="Object.keys(totalData).length > 0"
							:key="time"
							:total-data="totalData"
						></statistics>
					</el-tab-pane>
				</el-tabs>
				<!-- <div class="close" @click="close">
					<i
						class="el-icon-arrow-left"
						style="font-size:30px;    font-weight: bold;"
					></i>
				</div> -->
			</header>
		</div>
	</div>
</template>

<script>
import statistics from './statistics'
import list from '@/mixins/list'
// import { routerNames } from '@/utils/consts'

import dayjs from 'dayjs'

export default {
	// eslint-disable-next-line vue/name-property-casing
	name: 'editData',
	components: {
		statistics
	},
	mixins: [list],
	props: {
		showData: {
			type: Boolean,
			default: () => false
		},
		rowData1: {
			type: Object,
			default: () => {}
		}
	},
	data() {
		return {
			loading: false,
			rowData: {},
			activeName: 'first',
			totalData: {},
			time: Date.now(),
			// optionsValue: '',
			tableData: [],
			searchTime: [],
			queryData: {
				optionsValue: '',
				options: 'userName',
				searchTime: [],
				orderType: undefined,
				orderKey: undefined
			}
		}
	},
	created() {
		// this.loadPage()
		// this.loadPageTotal()
		const { query } = this.$route
		if (query && Object.keys(query).length > 0) {
			this.$nextTick(() => {
				this.rowData = { ...this.$route.query }
				this.loadPageTotal()
				const name = this.rowData.title || ''
				window.localStorage.setItem('routerName', name)

				if (this.rowData.activityType == 1) return
				if (+this.rowData.entranceEnable === 0) {
					this.activeName = 'second'
				}
			})
		}
	},
	mounted() {},
	methods: {
		typeFilter(code, name) {
			if (!code && code !== 0) return '-'
			return (
				this.globalDics[name]?.find((item) =>
					!isNaN(Number(code))
						? Number(item.code) === Number(code)
						: item.code === code
				)?.description || code
			)
		},
		filterAppID(val) {
			return {
				1: 'OB旗舰',
				2: '美播真人'
			}[val]
		},
		filterDeviceType(val) {
			return {
				1: 'PC',
				2: 'IOS_APP',
				3: 'IOS_H5',
				4: 'Android_H5',
				5: 'Android_APP',
				6: this.$t('operation.activity_list.backend')
			}[val]
		},
		// 改变列表条数
		handleSizeChange(value) {
			this.pageNum = 1
			this.pageSize = value
			this.loadPage()
		},
		handleCurrentChange(value) {
			this.pageNum = value
			this.loadData()
		},
		loadPageTotal() {
			// if (this.searchTime.length === 0) {
			// 	return this.$message({
			// 		type: 'warning',
			// 		message: '请先选择时间',
			// 		duration: 1500
			// 	})
			// }
			this.totalData = {}
			const [startTime, endTime] = this.searchTime || []
			const data = {
				activityId: this.rowData.id,
				merchantId: this.rowData.merchantId,
				visitTimeStart:
					(startTime &&
						dayjs(startTime).format('YYYY-MM-DD HH:mm:ss')) ||
					undefined,
				visitTimeEnd:
					(endTime && dayjs(endTime).format('YYYY-MM-DD HH:mm:ss')) ||
					undefined
			}

			this.$api
				.getActivityVisitDataStatistic(data)
				.then((res) => {
					if (res?.code === 200) {
						this.totalData = res.data
						this.time = Date.now()
					}
					this.loading = false
				})
				.catch(() => {
					this.loading = false
				})
		},
		loadPage() {
			if (
				!this.queryData.searchTime ||
				this.queryData.searchTime.length === 0
			) {
				return this.$message({
					type: 'warning',
					message: this.$t('operation.activity_list.select_time'),
					duration: 1500
				})
			}
			this.tableData = []
			const [startTime, endTime] = this.queryData.searchTime || []
			const params = {
				exportFlag: true,
				...this.getParams(),
				queryCondition: {
					...this.queryData,
					activityId: this.rowData.id,
					merchantId: this.rowData.merchantId,
					[this.queryData.options]: this.queryData.optionsValue,
					createdAtStart:
						(startTime &&
							dayjs(startTime).format('YYYY-MM-DD HH:mm:ss')) ||
						undefined,
					createdAtEnd:
						(endTime &&
							dayjs(endTime).format('YYYY-MM-DD HH:mm:ss')) ||
						undefined
				}
			}
			delete params.queryCondition.optionsValue
			delete params.queryCondition.options
			delete params.queryCondition.searchTime
			const handle =
				this.rowData.activityType == 1
					? this.$api.activityApplyRecordSCPage
					: this.$api.activityApplyRecordCZSPage
			handle(params)
				.then((res) => {
					if (res?.code === 200) {
						const { record, totalRecord } = res.data || {}
						this.tableData = record || []
						this.total = totalRecord || 0
					}
					this.loading = false
				})
				.catch(() => {
					this.loading = false
				})
		},
		handleClick(tab, event) {
			this.time = Date.now()
			if (
				tab.$options.propsData.name === 'second' ||
				this.activeName === 'second'
			) {
				this.loadPageTotal()
			}
		},
		search() {
			this.loadPage()
		},
		search1() {
			this.loadPageTotal()
		},
		reset() {
			// this.searchTime = []
			this.queryData = {
				optionsValue: '',
				options: 'userName',
				searchTime: [],
				orderType: undefined,
				orderKey: undefined
			}
			this.queryData.searchTime = []
			this.tableData = []
			// this.totalData = {}
			// this.loadPage()
			// this.loadPageTotal()
		},
		reset1() {
			this.searchTime = []
			// this.queryData = {
			// 	optionsValue: '',
			// 	options: 'parentProxyName',
			// 	searchTime: [],
			// 	...this.queryData
			// }
			// this.queryData.searchTime = []
			// this.tableData = []
			this.totalData = {}
			this.tableData = []
			this.loadPageTotal()
		},
		exportExcel() {
			if (
				!this.queryData.searchTime ||
				this.queryData.searchTime.length === 0
			) {
				return this.$message({
					type: 'warning',
					message: this.$t('operation.activity_list.select_time'),
					duration: 1500
				})
			}
			let create = []
			// eslint-disable-next-line no-const-assign
			create = this.queryData.searchTime || []
			const [startTime, endTime] = create
			const params = {
				...this.queryData,
				activityId: this.rowData.id,
				merchantId: this.rowData.merchantId,
				[this.queryData.options]: this.queryData.optionsValue,
				createdAtStart:
					(startTime &&
						dayjs(startTime).format('YYYY-MM-DD HH:mm:ss')) ||
					undefined,
				createdAtEnd:
					(endTime && dayjs(endTime).format('YYYY-MM-DD HH:mm:ss')) ||
					undefined
			}
			delete params.optionsValue
			delete params.options
			delete params.searchTime

			const handleAPI =
				this.rowData.activityType == 1
					? this.$api.activityApplyRecordSCdownload
					: this.$api.activityApplyRecordCZSdownload
			this.$confirm(
				`<strong>${this.$t(
					'operation.activity_list.is_export'
				)}?</strong></br><span style='font-size:12px;color:#c1c1c1'>${this.$t(
					'operation.activity_list.data_more'
				)}</span>`,
				this.$t('common.success_tip'),
				{
					dangerouslyUseHTMLString: true,
					confirmButtonText: this.$t('common.confirm'),
					cancelButtonText: this.$t('common.cancel'),
					type: 'warning'
				}
			)
				.then(() => {
					this.loading = true
					handleAPI(params)
						.then((res) => {
							this.loading = false
							const { data, status } = res
							if (res && status === 200) {
								const { type } = data
								if (type.includes('application/json')) {
									const reader = new FileReader()
									reader.onload = (evt) => {
										if (evt.target.readyState === 2) {
											const {
												target: { result }
											} = evt
											const ret = JSON.parse(result)
											if (ret.code !== 200) {
												this.$message({
													type: 'error',
													message: ret.msg,
													duration: 1500
												})
											}
										}
									}
									reader.readAsText(data)
								} else {
									const result = res.data
									const disposition =
										res.headers['content-disposition']
									const fileNames =
										disposition && disposition.split("''")
									let fileName = fileNames[1]
									fileName = decodeURIComponent(fileName)
									const blob = new Blob([result], {
										type: 'application/octet-stream'
									})
									if (
										'download' in
										document.createElement('a')
									) {
										const downloadLink = document.createElement(
											'a'
										)
										downloadLink.download = fileName || ''
										downloadLink.style.display = 'none'
										downloadLink.href = URL.createObjectURL(
											blob
										)
										document.body.appendChild(downloadLink)
										downloadLink.click()
										URL.revokeObjectURL(downloadLink.href)
										document.body.removeChild(downloadLink)
									} else {
										window.navigator.msSaveBlob(
											blob,
											fileName
										)
									}
									this.$message({
										type: 'success',
										message: this.$t(
											'operation.activity_list.export_success'
										),
										duration: 1500
									})
								}
							}
						})
						.catch(() => {
							this.loading = false
							// this.$message({
							//   type: "error",
							//   message: "导出失败",
							//   duration: 1500,
							// });
						})
				})
				.catch(() => {
					this.loading = false
				})
		},
		_changeTableSort({ column, prop, order }) {
			const obj = {
				createdAt: 0,
				updatedAt: 1
			}
			this.queryData.orderKey = obj[prop]
			if (order === 'ascending') {
				// 升序
				this.queryData.orderType = 'asc'
			} else if (column.order === 'descending') {
				// 降序
				this.queryData.orderType = 'desc'
			} else {
				delete this.queryData.orderKey
				delete this.queryData.orderType
			}
			// this.loadData()
			this.loadPage()
		},
		close() {
			this.$router.push({
				path: '/operation/activityManage/activityList'
			})
			// this.$emit('update:showData', false)
		}
	}
}
</script>

<style lang="scss" scoped>
header {
	position: relative;
	.close {
		width: 45px;
		height: 45px;
		position: absolute;
		right: 15px;
		top: 0;
		font-size: 25px;
		cursor: pointer;
	}
}
::v-deep .el-dialog__header {
	text-align: center;
	color: #909399;
	font-weight: 700;
}
</style>
